import axios from "axios";
import { message } from "antd"; // 使用 Ant Design 的提示
import Cookies from "js-cookie";

// 创建用于 JSON 数据请求的 axios 实例
const request = axios.create({
  baseURL: "/api",
  timeout: 120 * 1000,
  withCredentials: true,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
});

// 创建用于文件上传的 axios 实例
const fileRequest = axios.create({
  baseURL: "/api",
  timeout: 120 * 1000,
  withCredentials: true,
  headers: {
    Accept: "multipart/form-data",
    "Content-Type": "multipart/form-data",
  },
});

// 通用的请求拦截器
const addToken = (config) => {
  const token = Cookies.get("access_token");
  if (token) {
    config.headers["Authorization"] = `Bearer ${token}`;
  }
  return config;
};

// 通用的响应拦截器
const handleResponse = (response) => response.data;

export const handleError = (error, navigate) => {
  let errorMessage = "";
  const { response } = error;

  if (response) {
    const { status } = response;
    switch (status) {
      case 401:
        errorMessage = "未授权，请重新登录";
        Cookies.remove("access_token");
        if (navigate) navigate("/home");
        break;
      case 403:
        errorMessage = "禁止访问，权限不足";
        break;
      case 404:
        errorMessage = "请求的资源不存在";
        break;
      case 500:
        errorMessage = "服务器内部错误";
        break;
      default:
        errorMessage = response.data?.message || "请求失败";
    }
  } else {
    errorMessage = "请求配置错误：" + error?.message;
  }

  if (errorMessage) {
    message.error(errorMessage, 5); // 使用 Ant Design 的消息提示
    return Promise.reject(error); // 返回完整的错误对象
  } else {
    return Promise.reject(response);
  }
};

// 添加请求拦截器
request.interceptors.request.use(addToken, (error) => {
  // 请求错误处理
  return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(
  handleResponse,
  (error) => handleError(error) // 确保 handleError 被正确调用
);

fileRequest.interceptors.request.use(addToken, (error) => {
  return Promise.reject(error);
});

fileRequest.interceptors.response.use(handleResponse, (error) =>
  handleError(error)
);

export { request, fileRequest };
